import { clearAuthent, getAuthent } from "./utils";
import { TextDecoder } from "text-decoding";
export const baseConfig = {
  baseUrl: "http://fba.ansuex.com/api",
  subdomain: `fba.ansuex.com`,
  timeout: 60000,
};

const directLogin = () => {
  clearAuthent();
  uni.reLaunch({
    url: "/pages/login/index",
  });
};

export default function http(opts: Network.HttpOpts) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseConfig.baseUrl}${opts.url}`,
      method: opts.method.toLocaleUpperCase() as any,
      data: opts.data,
      header: {
        Authorization: getAuthent("token"),
        subdomain: baseConfig.subdomain,
        "Content-Type": "application/json",
        ...opts.headers,
      },
      responseType: opts.responseType,
      timeout: baseConfig.timeout,
      success: (res: any) => {
        // 处理 blob 和 arraybuffer 类型
        if (
          opts.responseType === "blob" ||
          opts.responseType === "arraybuffer"
        ) {
          if (res.header["Content-Type"].includes("application/json")) {
            const enc = new TextDecoder("utf-8");
            const bufferMsg = new Uint8Array(res.data);
            const result = enc.decode(bufferMsg);
            const { code, message } = JSON.parse(result);
            if (code === 401) {
              reject("身份信息过期请重新登录!");
              uni.showToast({
                title: "身份信息过期请重新登录!",
                icon: "none",
              });
              return directLogin();
            } else {
              reject(message ? message : "获取数据失败");
              return uni.showToast({
                title: message ? message : "获取数据失败",
                icon: "none",
                duration: 2000,
              });
            }
          } else {
            return resolve(res.data);
          }
        } else {
          // 处理其他类型
          const { code, message } = res.data;
          if (code === 200) {
            if (opts.hasAllRes) return resolve(res);
            return resolve(res.data);
          } else if (code === 401) {
            reject("身份信息过期请重新登录!");
            return directLogin();
          } else {
            reject(message ? message : "获取数据失败");
            if (!opts.customError) {
              uni.showToast({
                title: message ? message : "获取数据失败",
                icon: "none",
                duration: 2000,
              });
            }
          }
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}
// 文件上传
export function uploadFile(opts: Network.FormDataHttpOpts) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${baseConfig.baseUrl}${opts.url}`,
      header: {
        Authorization: getAuthent("token"), //自定义请求头信息
        subdomain: baseConfig.subdomain,
        ...opts.headers,
      },
      timeout: baseConfig.timeout,
      files: opts.files,
      file: opts.file,
      filePath: opts.filePath,
      formData: opts.formData,
      success: (res: any) => {
        const { code, message } = JSON.parse(res.data);
        if (code === 200) {
          return resolve(res.data);
        } else if (code === 401) {
          reject("身份信息过期请重新登录!");
          uni.showToast({
            title: "身份信息过期请重新登录!",
            icon: "none",
          });
          return directLogin();
        } else {
          reject(message ? message : "获取数据失败");
          return uni.showToast({
            title: message ? message : "获取数据失败",
            icon: "none",
            duration: 2000,
          });
        }
      },
      fail: (err: any) => {
        reject(err);
      },
    });
  });
}
